<template>
  <div class="list" ref="list">
    <ul>
      <li
        class="item"
        v-for="(val, key) in alphabetList"
        :key="key"
        v-text="key"
        :ref="key"
        @click="handleClick(key)"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    alphabetList: {
      required: true,
      type: Object
    }
  },
  data () {
    return {
      watchMove: false,
      oldIndex: null,
      startY: 0,
      listTop: 0,
      domHeight: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs[this.letters[0]][0].offsetTop
    this.listTop = this.$refs.list.offsetTop
    this.domHeight = this.$refs['A'][0].offsetHeight
  },
  computed: {
    letters: function () {
      return Object.keys(this.alphabetList)
    }
  },
  methods: {
    handleClick: function (val) {
      this.$emit('scrollInto', val)
    },
    handleTouchStart: function () {
      this.watchMove = true
    },
    handleTouchMove: function (e) {
      if (this.watchMove) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - this.listTop
          const index = Math.floor((touchY - this.startY) / this.domHeight)
          if (
            index > -1 &&
            index < this.letters.length &&
            index !== this.oldIndex
          ) {
            this.oldIndex = index
            this.$emit('scrollInto', this.letters[index])
          }
        }, 15)
      }
    },
    handleTouchEnd: function () {
      this.watchMove = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@styles/varibles.styl'
.list{
  position absolute
  top 1.64rem
  right 0
  bottom 0
  width 0.4rem
  text-align center
  display flex
  align-items center
  justify-content center
  ul{
    line-height .44rem
    color $bgColor
    font-weight bold
  }
}
</style>
